package com.softstao.guoyu.base;

import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.softstao.guoyu.R;
import com.softstao.guoyu.accept.Accept;
import com.softstao.guoyu.accept.AcceptType;
import com.softstao.guoyu.mvp.events.ActionEvent;
import com.softstao.guoyu.mvp.rxbus.RxBusAnnotationManager;
import com.softstao.softstaolibrary.library.utils.LZUtils;
import com.softstao.softstaolibrary.library.widget.TitleBar;
import com.wangjie.androidbucket.customviews.borderscrollview.OnScrollChangedListener;
import com.wangjie.androidinject.annotation.core.base.AnnotationManager;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler2;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.header.StoreHouseHeader;

/**
 * Created by zhanghongbo on 15-11-13.
 */
public abstract class BaseFragment extends ParentFragment implements PtrHandler2, OnScrollChangedListener {
    //    protected IMPreference preference;
    private RxBusAnnotationManager rxBusAnnotationManager;
    private AnnotationManager annotationManager;
    protected Context mContext;
    protected TitleBar titleBar;
    protected PtrFrameLayout ptrFrameLayout;
    protected int pageSize = 8;
    protected int offset = 1;
    protected int currentPage = 1;
    private int yScroll = 0;
    private int imageHeight;
    protected int statusBarHeight;
    protected SystemBarTintManager tintManager ;

    protected boolean isCan=false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        imageHeight = LZUtils.dipToPix(mContext, 140);
        tintManager = new SystemBarTintManager(getActivity());
        statusBarHeight=tintManager.getConfig().getStatusBarHeight();
    }

    public void setTitleBar(String title) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            titleBar = getFragmentManager().findFragmentById(R.id.title) != null ? (TitleBar) getFragmentManager().findFragmentById(R.id.title) : (TitleBar) getChildFragmentManager().findFragmentById(R.id.title);
        }
        showTitleBar(true);
        titleBar.setThemeColor(getResources().getColor(R.color.colorPrimary));
        titleBar.getDivider().setVisibility(View.VISIBLE);
//        titleBar.setLeftIcon(R.mipmap.back);
//        titleBar.setBackButtonVisible();
        titleBar.setTitle(title);
        titleBar.setFontColor(getResources().getColor(R.color.font_black));
        titleBar.setTitileBackgroundColor(getResources().getColor(R.color.colorPrimary));
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) titleBar.getMainView().getLayoutParams();
        lp.setMargins(0,statusBarHeight,0,0);
        titleBar.getMainView().setLayoutParams(lp);
    }

    public void showTitleBar(boolean show) {
        FragmentTransaction ft = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            ft = getFragmentManager().beginTransaction() != null ? getFragmentManager().beginTransaction() : getChildFragmentManager().beginTransaction();
        }
        if (show) {
            ft.show(titleBar);
        } else {
            ft.hide(titleBar);
        }
//        ft.commit();
        ft.commitAllowingStateLoss();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(_ContentView(), container, false);
        ButterKnife.bind(this, view);
        ptrFrameLayout = (PtrFrameLayout) view.findViewById(R.id.ptr_frame);
//        adView = (ImageCycleView) view.findViewById(R.id.ad_view);
        initView();
        return view;
    }

    public abstract int _ContentView();

    public abstract void initView();

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onResume() {
        super.onResume();
        initAnnotations();
        if (rxBusAnnotationManager == null) {
            rxBusAnnotationManager = new RxBusAnnotationManager(this);
        }
        try {
            Method method = this.getClass().getMethod("error", Object.class, Object.class);
            rxBusAnnotationManager.parserObservableEventAnnotations(method);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        clearAnnotations();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void setContentView_(int i) {

    }

    @Override
    public View findViewById_(int i) {
        return null;
    }

    @Override
    public void parserTypeAnnotations(Class aClass) throws Exception {

    }

    @Override
    public void parserMethodAnnotations(Method method) throws Exception {
        if (method.isAnnotationPresent(Accept.class)) {
            if (null == rxBusAnnotationManager) {
                rxBusAnnotationManager = new RxBusAnnotationManager(this);
            }
            rxBusAnnotationManager.parserObservableEventAnnotations(method);
        }
    }

    @Override
    public void parserFieldAnnotations(Field field) throws Exception {

    }

    private void initAnnotations() {
        if (annotationManager == null) {
            annotationManager = new AnnotationManager(this);
        }
        try {
            annotationManager.initAnnotations();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void clearAnnotations() {
        closeAllTask();
        if (null != rxBusAnnotationManager) {
            rxBusAnnotationManager.clear();
        }
    }

    protected void setPtrFrameLayoutEnable() {
        StoreHouseHeader header = new StoreHouseHeader(mContext);
        header.setPadding(0, 55, 0, 55);
        header.initWithString(getString(R.string.app_name_en));
        header.setTextColor(getResources().getColor(R.color.theme_color));
        header.setScale(1.7f);
        header.onUIReset(ptrFrameLayout);
        ptrFrameLayout.setHeaderView(header);
        ptrFrameLayout.addPtrUIHandler(header);
        ptrFrameLayout.setPtrHandler(this);
    }

    protected void setPtrFrameLayoutFooter() {
        StoreHouseHeader footer = new StoreHouseHeader(mContext);
        footer.setPadding(0, 50, 0, 50);
        footer.initWithString(getString(R.string.app_name_en));
        footer.setTextColor(getResources().getColor(R.color.theme_color));
        footer.setScale(1.7f);
        footer.onUIReset(ptrFrameLayout);
        ptrFrameLayout.setFooterView(footer);
        ptrFrameLayout.addPtrUIHandler(footer);
    }

    //不足
    protected void setHeaderView(View header) {
        ptrFrameLayout.setHeaderView(header);
        ptrFrameLayout.addPtrUIHandler((PtrUIHandler) header);
    }

    protected void setFooterView(View footer) {
        ptrFrameLayout.setFooterView(footer);
        ptrFrameLayout.addPtrUIHandler((PtrUIHandler) footer);
    }

    @Override
    public void onLoadMoreBegin(PtrFrameLayout frame) {
        onLoad();
        frame.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrFrameLayout.refreshComplete();
                ptrFrameLayout.requestLayout();
            }
        }, 1800);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        onRefresh();
        frame.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrFrameLayout.refreshComplete();
                ptrFrameLayout.requestLayout();
            }
        }, 1800);
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler2.checkContentCanBePulledDown(frame, content, header);
    }

    @Override
    public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
        return PtrDefaultHandler2.checkContentCanBePulledUp(frame, content, footer);
    }

    public void onRefresh() {
//        emptyLayout.setVisibility(View.GONE);
        currentPage = 1;
        offset = 1;
    }

    public void onLoad() {
//        emptyLayout.setVisibility(View.GONE);
        currentPage++;
        offset = currentPage * pageSize;
    }

    @Accept(
            value = {
                    @AcceptType(tag = ActionEvent.REFRESH_OR_LOAD_FINISH, clazz = String.class)
            }
    )
    public void error(Object tag, Object event) {
        switch (tag.toString()) {
            case ActionEvent.REFRESH_OR_LOAD_FINISH:
                if (ptrFrameLayout != null) {
                    ptrFrameLayout.refreshComplete();
                    ptrFrameLayout.requestLayout();
                }
                break;
        }
    }

    public int getScreenWidth() {
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int height = displaymetrics.heightPixels;
        int width = displaymetrics.widthPixels;

        return width;
    }

    @Override
    public void onScrollChanged(int i, int i1, int i2, int i3) {
        yScroll = i1;
        if(isCan){
            if (i1 <= 0) {
                if (titleBar!=null) {
                    titleBar.setBackgroundColor(Color.TRANSPARENT);//AGB由相关工具获得，或者美工提供
                }
            } else if (i1 > 0 && i1 <= imageHeight) {
                float scale = (float) i1 / imageHeight;
                float alpha = (255 * scale);
                // 只是layout背景透明(仿知乎滑动效果)
                if (titleBar!=null) {
                    titleBar.setBackgroundColor(Color.argb((int) alpha, 255, 255, 255));
                }
            } else {
                if (titleBar!=null) {
                    titleBar.setBackgroundColor(Color.argb((int) 255, 255, 255, 255));
                }
            }
        }
    }

    @Override
    public void onScrollTop() {
    }

    @Override
    public void onScrollBottom() {
        onLoad();
    }

    public int getImageHeight() {
        return imageHeight;
    }

    public void setImageHeight(int imageHeight) {
        this.imageHeight = imageHeight;
    }

    @Override
    public Context getContext() {
        return mContext;
    }

    public boolean isCan() {
        return isCan;
    }

    public void setCan(boolean can) {
        isCan = can;
    }
}

